﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using SapB1WebPOS.BLL;
using System.Data;
using Newtonsoft.Json;
using System.Web.Script.Services;
using SapB1WebPOS.Utils;
using SapB1WebPOS.DAL;

namespace SapB1WebPOS
{
    public partial class SalesQuotation : System.Web.UI.Page
    {
        public class Response
        {
            public List<Model.QUT1> Data { get; set; }
            public int Count { get; set; }
            public string Errors { get; set; }

            public Response(List<Model.QUT1> data, int count)
            {
                this.Data = data;
                this.Count = count;
            }

            public Response(string errors)
            {
                this.Errors = errors;
            }

            public Response()
            {

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string GetSAPItemPrice(string cardCode, string itemCode, float amount, DateTime refDate)
        {
            try
            {
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (sapUser.Length > 0 && sapPassword.Length > 0 && companyDB.Length > 0)
                {
                    SAPTransaction obj = new SAPTransaction();
                    return obj.GetSAPItemPrice(sapUser, sapPassword, companyDB, cardCode, itemCode, amount, refDate).ToString();
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
                return "0";
            }
            return "0";
        }
        [WebMethod]
        public static string GetWareHouses()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();
                    DataSet dsData = obj.GetWareshouse(companyDB);
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetTaxs()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();
                    DataSet dsData = obj.GetTax(companyDB, "O");
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetItemMasterDataByItemCode(string itemCode)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    ItemMasterDataBLL obj = new ItemMasterDataBLL();
                    DataSet dsData = obj.GetOITMByItemCode(companyDB, itemCode);
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void ClearSessionData()
        {
            HttpContext.Current.Session["DocList"] = null;
            HttpContext.Current.Session["DocCount"] = null;
            HttpContext.Current.Session["DeleteDocList"] = null;
            HttpContext.Current.Session["DataType"] = null;
            HttpContext.Current.Session["PrintLineData"] = null;
            HttpContext.Current.Session["PrintHeaderData"] = null;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string CancelDoc(string docEntry)
        {
            try
            {
                SAPTransaction obj = new SAPTransaction();
                DataTable tbResult = new DataTable();
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (sapUser.Length > 0 && sapPassword.Length > 0 && companyDB.Length > 0)
                {
                    string docType = ConvertDocType.Get2String(DocType.SALES_QUOTATION);
                    tbResult = obj.CloseCancelDocument(sapUser, sapPassword,companyDB, docType, docEntry, true);
                    if (tbResult != null && tbResult.Rows.Count > 0)
                    {
                        if ((int)tbResult.Rows[0]["ErrCode"] != 0)
                        {
                            return "Error: " + tbResult.Rows[0]["ErrMsg"].ToString();
                        }
                        else
                        {
                            return tbResult.Rows[0]["ErrMsg"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return docEntry;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string UpdateDocToDB(string oDocHeader, bool isUpdate, string docEntry)
        {
            try
            {
                Model.OQUT header = JsonConvert.DeserializeObject<Model.OQUT>(oDocHeader);
                List<Model.QUT1> lstDocLine = new List<Model.QUT1>();
                List<Model.QUT1> lstDeleteDocLine = new List<Model.QUT1>();
                DataTable tbDeleteLine = null;
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    lstDocLine = (List<Model.QUT1>)HttpContext.Current.Session["DocList"];
                }
                if (HttpContext.Current.Session["DeleteDocList"] != null)
                {
                    lstDeleteDocLine = (List<Model.QUT1>)HttpContext.Current.Session["DeleteDocList"];
                }
                if (header != null)
                {
                    string loginUser = string.Empty;
                    string loginPass = string.Empty;
                    string companyDB = string.Empty;
                    if (HttpContext.Current.Session["LoginUserName"] != null)
                    {
                        loginUser = HttpContext.Current.Session["LoginUserName"].ToString();
                    }
                    if (HttpContext.Current.Session["LoginPassword"] != null)
                    {
                        loginPass = HttpContext.Current.Session["LoginPassword"].ToString();
                    }
                    if (HttpContext.Current.Session["CompanyDB"] != null)
                    {
                        companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                    }

                    DataTable tbHeader = new DataTable(Utils.TableNameDefined.SALES_QUOTATION_HEADER);
                    tbHeader.Columns.Add("DocEntry");
                    tbHeader.Columns.Add("CardCode");
                    tbHeader.Columns.Add("CardName");
                    tbHeader.Columns.Add("DocDate");
                    tbHeader.Columns.Add("DocDueDate");
                    tbHeader.Columns.Add("TaxDate");
                    tbHeader.Columns.Add("Comments");
                    if (!(bool)HttpContext.Current.Session["IsSAPUser"])
                    {
                        tbHeader.Columns.Add("U_WebUser");
                    }

                    DataRow rHeader = tbHeader.NewRow();

                    rHeader["DocEntry"] = header.DocEntry;
                    rHeader["CardCode"] = header.CardCode;
                    rHeader["CardName"] = header.CardName;
                    rHeader["DocDate"] = header.DocDate.ToString(Utils.Utils.SAP_FORMAT_DATE);
                    rHeader["DocDueDate"] = header.DocDueDate.ToString(Utils.Utils.SAP_FORMAT_DATE);
                    rHeader["TaxDate"] = header.TaxDate.ToString(Utils.Utils.SAP_FORMAT_DATE);
                    rHeader["Comments"] = header.Comments;
                    if (!(bool)HttpContext.Current.Session["IsSAPUser"])
                    {
                        rHeader["U_WebUser"] = loginUser;
                    }

                    tbHeader.Rows.Add(rHeader);


                    DataTable tbLine = Utils.Utils.ToDataTable<Model.QUT1>(lstDocLine);

                    tbLine.Columns.Remove("OnHand");
                    tbLine.Columns.Remove("TotalBefDisc");
                    tbLine.Columns.Remove("Total");
                    tbLine.Columns.Remove("LineStatus");
                    tbLine.Columns.Remove("VatGroupName");
                    tbLine.Columns.Remove("WhsName");
                    tbLine.Columns.Remove("BaseEntry");
                    tbLine.Columns.Remove("BaseLine");
                    tbLine.Columns.Remove("BaseType");

                    DataSet dsUpdate = new DataSet();
                    dsUpdate.Tables.Add(tbHeader);
                    dsUpdate.Tables.Add(tbLine);


                    if (lstDeleteDocLine.Count > 0)
                    {
                        tbDeleteLine = Utils.Utils.ToDataTable<Model.QUT1>(lstDeleteDocLine);
                    }

                    string docType = ConvertDocType.Get2String(DocType.SALES_QUOTATION);
                    string xml = DocumentXML.ToXMLStringFromDS(docType, dsUpdate);
                    if (xml.Length > 0)
                    {
                        SAPTransaction obj = new SAPTransaction();
                        DataTable tbResult = new DataTable();
                      
                        if (loginUser.Length > 0 && loginPass.Length > 0 && companyDB.Length > 0)
                        {
                            //Delete
                            //if (tbDeleteLine != null)
                            //{
                            //    tbResult = obj.DeleteMarketingDocument(sapUser, sapPassword, tbDeleteLine, docType, docEntry);
                            //    if (tbResult != null && tbResult.Rows.Count > 0)
                            //    {
                            //        if ((int)tbResult.Rows[0]["ErrCode"] != 0)
                            //        {
                            //            return "Error:" + tbResult.Rows[0]["ErrMsg"].ToString();
                            //        }
                            //    }
                            //}
                            //Update
                            tbResult = obj.CreateMarketingDocument(loginUser, loginPass,companyDB, xml, docType, docEntry, isUpdate);

                            if (tbResult != null && tbResult.Rows.Count > 0)
                            {
                                if ((int)tbResult.Rows[0]["ErrCode"] != 0)
                                {
                                    return "Error: " + tbResult.Rows[0]["ErrMsg"].ToString();
                                }
                                else
                                {
                                    if (!isUpdate)
                                    {
                                        return tbResult.Rows[0]["ErrMsg"].ToString();
                                    }
                                    else
                                    {
                                        return docEntry;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        return "Please input item.";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return "0";
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static void DeleteDocLine(string lineNum)
        {
            try
            {
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    List<Model.QUT1> lstDocLine = (List<Model.QUT1>)HttpContext.Current.Session["DocList"];
                    Model.QUT1 updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == lineNum);
                    if (updateLine.DocEntry.Length > 0)
                    {
                        List<Model.QUT1> lstDeleteDocLine;
                        if (HttpContext.Current.Session["DeleteDocList"] != null)
                        {
                            lstDeleteDocLine = (List<Model.QUT1>)HttpContext.Current.Session["DeleteDocList"];
                        }
                        else
                        {
                            lstDeleteDocLine = new List<Model.QUT1>();
                        }
                        lstDeleteDocLine.Add(updateLine);
                        HttpContext.Current.Session["DeleteDocList"] = lstDeleteDocLine;
                        lstDocLine.Remove(updateLine);
                    }
                    else
                    {
                        lstDocLine.Remove(updateLine);
                    }
                    HttpContext.Current.Session["DocList"] = lstDocLine;
                    HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void UpdateDoc(string oDocLine, string isInsert, string rowIndex)
        {
            try
            {
                Model.QUT1 line = JsonConvert.DeserializeObject<Model.QUT1>(oDocLine);
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    List<Model.QUT1> lstDocLine = (List<Model.QUT1>)HttpContext.Current.Session["DocList"];
                    var result = (from m in lstDocLine
                                  select m).OrderByDescending(a => a.LineNum).FirstOrDefault(); ;
                    if (isInsert == "1")
                    {
                        if (result != null)
                        {
                            line.LineNum = (int.Parse(result.LineNum) + 1).ToString();
                        }
                        else
                        {
                            line.LineNum = "0";
                        }
                        lstDocLine.Add(line);
                    }
                    else if (isInsert == "2")
                    {
                        Model.QUT1 updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == line.LineNum);
                        int index = lstDocLine.FindIndex(u => u.LineNum == line.LineNum);
                        updateLine.ItemCode = line.ItemCode;
                        updateLine.Dscription = line.Dscription;
                        updateLine.Quantity = line.Quantity;
                        updateLine.WhsCode = line.WhsCode;
                        updateLine.WhsName = line.WhsName;
                        updateLine.VatGroup = line.VatGroup;
                        updateLine.VatGroupName = line.VatGroupName;
                        updateLine.LineTotal = line.LineTotal;
                        updateLine.DiscPrcnt = line.DiscPrcnt;
                        updateLine.PriceBefDi = line.PriceBefDi;
                        updateLine.TotalBefDisc = line.TotalBefDisc;
                        updateLine.Price = line.Price;
                        updateLine.unitMsr = line.unitMsr;
                        updateLine.DocEntry = line.DocEntry;
                        updateLine.LineNum = line.LineNum;
                        updateLine.Total = line.Total;
                        updateLine.VatSum = line.VatSum;
                    }
                    HttpContext.Current.Session["DocList"] = lstDocLine;
                    HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static Response GetDocLines(string docEntry)
        {
            try
            {
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    List<Model.QUT1> lstDocLineUpdate = (List<Model.QUT1>)HttpContext.Current.Session["DocList"];
                    List<Model.QUT1> filteredResults = lstDocLineUpdate.FindAll(p => p.LineStatus != "3");
                    HttpContext.Current.Session["DocList"] = filteredResults;
                    HttpContext.Current.Session["DocCount"] = filteredResults.Count;
                    return new Response(filteredResults, filteredResults.Count);
                }
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    List<Model.QUT1> lstDocLine = new List<Model.QUT1>();
                    SalesQuotationBLL obj = new SalesQuotationBLL();
                    DataSet dsData = obj.GetQUT1ByDocEntry(companyDB, docEntry);
                    if (dsData != null)
                    {
                        HttpContext.Current.Session["PrintLineData"] = dsData.Tables[0].Copy();
                        foreach (DataRow r in dsData.Tables[0].Rows)
                        {
                            Model.QUT1 docLine = new Model.QUT1();
                            docLine.DocEntry = r["DocEntry"].ToString();
                            docLine.DiscPrcnt = double.Parse(r["DiscPrcnt"].ToString());
                            docLine.Dscription = r["Dscription"].ToString();
                            docLine.ItemCode = r["ItemCode"].ToString();
                            docLine.LineNum = r["LineNum"].ToString();
                            docLine.LineStatus = r["LineStatus"].ToString();
                            docLine.LineTotal = double.Parse(r["LineTotal"].ToString());
                            docLine.Price = double.Parse(r["Price"].ToString());
                            docLine.PriceBefDi = double.Parse(r["PriceBefDi"].ToString());
                            docLine.Quantity = double.Parse(r["Quantity"].ToString());
                            docLine.unitMsr = r["unitMsr"].ToString();
                            docLine.VatGroup = r["VatGroup"].ToString();
                            docLine.VatGroupName = r["VatGroupName"].ToString();
                            docLine.VatPrcnt = double.Parse(r["VatPrcnt"].ToString());
                            docLine.VatSum = double.Parse(r["VatSum"].ToString());
                            docLine.WhsCode = r["WhsCode"].ToString();
                            docLine.WhsName = r["WhsName"].ToString();

                            double totalBeforeDiscount = double.Parse(r["Quantity"].ToString()) * double.Parse(r["PriceBefDi"].ToString());
                            docLine.TotalBefDisc = totalBeforeDiscount;

                            double total = double.Parse(r["LineTotal"].ToString()) + double.Parse(r["VatSum"].ToString());
                            docLine.Total = total;

                            lstDocLine.Add(docLine);
                        }
                        HttpContext.Current.Session["DocList"] = lstDocLine;
                        HttpContext.Current.Session["DocCount"] = dsData.Tables[0].Rows.Count;
                        var jsonData = new { total = dsData.Tables[0].Rows.Count, lstCustomerProperty = lstDocLine };
                        return new Response(lstDocLine, dsData.Tables[0].Rows.Count);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return new Response();
        }
        [WebMethod]
        public static string GetDocHeaderByDocEntry(string docEntry)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    if (docEntry != null && docEntry.Length > 0)
                    {
                        SalesQuotationBLL obj = new SalesQuotationBLL();
                        DataSet dsData = obj.GetOQUTByDocEntry(companyDB, docEntry);
                        if (dsData != null)
                        {
                            return JsonConvert.SerializeObject(dsData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetLastRecord()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    SalesQuotationBLL obj = new SalesQuotationBLL();
                    DataSet dsData = obj.GetOQUTLastRecord(companyDB);
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetPDF(string docEntry)
        {
            try
            {
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                string companyName = string.Empty;

                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (HttpContext.Current.Session["CompanyName"] != null)
                {
                    companyName = HttpContext.Current.Session["CompanyName"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    SalesQuotationBLL obj = new SalesQuotationBLL();
                    DataSet dsData = new DataSet();
                    string html = string.Empty;

                    DataTable tbHeader = null;
                    DataTable tbLine = null;
                    if (HttpContext.Current.Session["PrintHeaderData"] != null)
                    {
                        tbHeader = ((DataTable)HttpContext.Current.Session["PrintHeaderData"]).Copy();
                    }
                    else
                    {
                        DataSet dsHeader = obj.GetOQUTByDocEntry(companyDB, docEntry);
                        if (dsHeader != null && dsHeader.Tables.Count > 0)
                        {
                            tbHeader = dsHeader.Tables[0].Copy();
                            HttpContext.Current.Session["PrintHeaderData"] = tbHeader;
                        }
                    }
                    if (HttpContext.Current.Session["PrintLineData"] != null)
                    {
                        tbLine = ((DataTable)HttpContext.Current.Session["PrintLineData"]).Copy();
                    }
                    if (tbHeader != null && tbLine != null)
                    {
                        tbHeader.TableName = Utils.TableNameDefined.PURCHASE_ORDER_HEADER;
                        tbLine.TableName = Utils.TableNameDefined.PURCHASE_ORDER_LINE;

                        dsData.Tables.Add(tbHeader);
                        dsData.Tables.Add(tbLine);

                        html = obj.CreateHTML(dsData, companyDB, sapUser, companyName, HttpContext.Current.Server.MapPath("html/SalesQuotation.html"));
                        return html;
                    }
                    else
                    {
                        return "Error: Can not print.";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
                return "Error: " + ex.Message;
            }
            return string.Empty;
        }
    }
}